<!-- 前端计算-组件 -->
<template>
  <div>
    {{ result }}
  </div>
</template>

<script>
export default {
  name: 'FrontCompute',
  inject: {
    elForm: {
      default: () => {
        return {}
      }
    }
  },
  props: {
    value: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
    }
  },
  computed: {
    result() {
      const { computeWay, computeAttrList } = this.$attrs
      const valueList = []
      const { model } = this.elForm
      if (model) { // 点击"预览"时，执行
        for (const key in model) {
          computeAttrList.includes(key) && valueList.push(model[key])
        }
      }
      //  else { // 拖拽到中间时，在中间预览效果
      //   valueList = computeAttrList.map(item => item.__config__.defaultValue)
      // }
      const obj = this.countModel()
      const count = valueList.length ? obj[computeWay](valueList) : 0
      this.$emit('input', count)
      return count
    }
  },
  methods: {
    countModel() {
      const sum = (valueList) => {
        return valueList.reduce((pre, item) => {
          pre += item
          return pre
        }, 0)
      }
      const amass = (valueList) => {
        return valueList.reduce((pre, item) => {
          pre *= item
          return pre
        }, 1)
      }
      const obj = { // 1:和；2：求积，3：平均值，4：最大值，5：最小值
        1: sum,
        2: amass,
        3: (valueList) => {
          return (sum(valueList) / (valueList.length || 1)).toFixed(2)
        },
        4: (valueList) => {
          return Math.max(...valueList)
        },
        5: (valueList) => {
          return Math.min(...valueList)
        }
      }
      return obj
    }
  }
}
</script>

  <style type="text/css" scoped>
  </style>

